import asyncio
import logging
import logging.config

import tornado
import tornado.web

from conf import CONFIG

try:
    from conf.debug_logging import get_logging
except ImportError:
    from conf.logging import get_logging

from pubsub.brokers.rabbitmq import RabbitConnection
from webutils.layers.db import get_db_proxy_cls

from .urls import urlpatterns

tornado.ioloop.IOLoop.configure("tornado.platform.asyncio.AsyncIOLoop")
io_loop = tornado.ioloop.IOLoop.current()
asyncio.set_event_loop(io_loop.asyncio_loop)


async def make_app(log_level, log_filename, **settings):
    logging_config = get_logging(log_level, log_filename)
    logging.config.dictConfig(logging_config)

    # 数据库初始化
    db_mapping = {}
    for db_config in CONFIG['database']:
        conn_cls = get_db_proxy_cls(db_config['type'])
        conn = conn_cls(db_config['url'], **db_config['kwargs'])
        await conn.initialize()
        db_mapping[db_config['name']] = conn
    settings['DB_MAPPING'] = db_mapping

    # rabbitmq 开启
    rabbitmq_url = CONFIG['RABBITMQ.URL']
    broadcaster_backend = RabbitConnection(rabbitmq_url)
    await broadcaster_backend.start()
    settings['RABBITMQ'] = broadcaster_backend
    settings['websocket_ping_interval'] = 30

    return tornado.web.Application(urlpatterns, **settings)
